package com.pig4cloud.pig.ads.controller;

import com.pig4cloud.pig.ads.service.AdAccountService;
import com.pig4cloud.pig.ads.service.AdTtTransferService;
import com.pig4cloud.pig.api.dto.AdTtTransferDto;
import com.pig4cloud.pig.api.vo.AdTtadvertiserVO;
import com.pig4cloud.pig.common.core.util.R;
import io.swagger.annotations.Api;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * @author ：lile
 * @date ：2021/7/15 14:37
 * @description：
 * @modified By：
 */
@RestController
@AllArgsConstructor
@RequestMapping("/transfer")
@Api(value = "transfer", tags = "头条转账")
public class AdTtTransferController {

	@Autowired
	private AdTtTransferService adTtTransferService;


	/**
	 * 头条 广告账户  转账
	 */
	@RequestMapping("/tt")
	public R addTtAdTransfer(@RequestBody AdTtTransferDto ato) {
		try {
			validCondition(ato);
			return adTtTransferService.addTtAdTransfer(ato);
		} catch (Exception e) {
			return R.failed(e.getMessage());
		}
	}

	/**
	 * 参数空值校验
	 *
	 * @param ato
	 * @throws Exception
	 */
	public void validCondition(AdTtTransferDto ato) throws Exception {

		if (Objects.isNull(ato.getAdvertiserId())) {
			throw new Exception("目标广告账户为空");
		}
		if (Objects.isNull(ato.getAdvertiserIdFrom())) {
			throw new Exception("转出广告账户为空");
		}
		if (StringUtils.isBlank(ato.getTransferType())) {
			throw new Exception("转账类型为空");
		}
		if (Objects.isNull(ato.getAmount())) {
			throw new Exception("转账金额为空");
		}
		if (Objects.isNull(ato.getBalance())) {
			throw new Exception("余额为空");
		}
		if (ato.getBalance().equals(BigDecimal.ZERO)) {
			throw new Exception("余额为零，不能转账");
		}
		if (ato.getBalance().intValue() <= ato.getAmount()) {
			throw new Exception("账户余额少于转账余额");
		}
		AdTtadvertiserVO adTtadvertiserVO = adTtTransferService.getTtBalance(ato.getAdvertiserIdFrom());
		if (adTtadvertiserVO == null) {
			throw new Exception("实际转账账户余额为空,请刷新页面");
		}
		if (adTtadvertiserVO != null) {
			if (ato.getTransferType().equals("CASH")) {
				if (adTtadvertiserVO.getValidCash() == BigDecimal.ZERO) {
					throw new Exception("实际现金余额为零,请刷新页面");
				}
			}
			if (ato.getTransferType().equals("GRANT")) {
				if (adTtadvertiserVO.getValidCash() == BigDecimal.ZERO) {
					throw new Exception("实际赠款余额为零,请刷新页面");
				}
			}
			if (ato.getTransferType().equals("CASH")) {
				if (ato.getBalance() != adTtadvertiserVO.getValidCash()) {
					throw new Exception("实际现金余额和当前页面余额不一致,请刷新页面");
				}
			}
			if (ato.getTransferType().equals("GRANT")) {
				if (ato.getBalance() != adTtadvertiserVO.getValidGrant()) {
					throw new Exception("实际赠款余额和当前页面赠款余额不一致,请刷新页面");
				}
			}
		}
	}
}
